package com.bw.lib_check_wdy_xin.listview

import android.os.Bundle
import android.widget.CheckBox
import android.widget.ListView
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bw.lib_check_wdy_xin.R

class ListCheckActivity : AppCompatActivity() {
    private lateinit var adapter: CheckboxListAdapter
    private lateinit var list_box_wdy : CheckBox
    private lateinit var list_tv_wdy : TextView
    private val items = mutableListOf<CheckboxItem>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_list_check)

        //处理系统栏
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        //初始化视图
        val list_view_wdy = findViewById<ListView>(R.id.list_view_wdy)
        list_box_wdy = findViewById(R.id.list_box_wdy)
        list_tv_wdy = findViewById(R.id.list_tv_wdy)

        // 准备数据
        for (i in 1 .. 20){
            items.add(CheckboxItem("选项: $i"))
        }

        // 设置适配器
        adapter = CheckboxListAdapter(items){position,isChecked ->
            items[position].isChecked = isChecked
            updateUI()
        }
        list_view_wdy.adapter = adapter

        // 设置全选按钮
        list_box_wdy.setOnCheckedChangeListener { _, b ->
            adapter.updataAllItems(b)
            updateUI()
        }

        // 初始化UI
        updateUI()
    }
    private fun updateUI(){
        val checkedCount = items.count { it.isChecked }
        list_tv_wdy.text = "已选择: $checkedCount"

        // 更新全选框状态.
        list_box_wdy.setOnCheckedChangeListener(null)
        list_box_wdy.isChecked = checkedCount == items.size
        list_box_wdy.setOnCheckedChangeListener { _, b ->
            adapter.updataAllItems(b)
            updateUI()
        }
    }
}